package utils

import (
	"context"
	"fmt"
	"github.com/olivere/elastic/v7"
)

var ES *elastic.Client

func init() {
	var err error
	ES, err = elastic.NewClient(elastic.SetURL("http://10.3.188.3:9200"), elastic.SetSniff(false))
	if err != nil {
		panic(err)
	}
}

const mapping = `
{
	"settings":{
		"number_of_shards": 1,
		"number_of_replicas": 0
	},
	"mappings":{
		"tweet":{
			"properties":{
				"user":{
					"type":"keyword"
				},
				"message":{
					"type":"text",
					"store": true,
					"fielddata": true
				},
				"image":{
					"type":"keyword"
				},
				"created":{
					"type":"date"
				},
				"tags":{
					"type":"keyword"
				},
				"location":{
					"type":"geo_point"
				},
				"suggest_field":{
					"type":"completion"
				}
			}
		}
	}
}`

// 创建index
func CreateIndex(ctx context.Context, index string) error {
	exists, err := ES.IndexExists(index).Do(ctx)
	if err != nil {
		// Handle error
		panic(err)
	}
	if !exists {
		_, err = ES.CreateIndex(index).BodyString(mapping).Do(ctx)
		if err != nil {
			panic(err)
		}
	}

	return nil
}

func PutData(ctx context.Context, index, id string, body interface{}) error {
	_, err := ES.Index().
		Index("twitter").
		Id("1").
		BodyJson(body).
		Do(ctx)
	if err != nil {
		return err
	}
	return nil
}

func SearchData(ctx context.Context, index, key, vale string) error {
	termQuery := elastic.NewTermQuery("user", "olivere")
	searchResult, err := ES.Search().
		Index(index).       // search in index "twitter"
		Query(termQuery).   // specify the query
		Sort("user", true). // sort by "user" field, ascending
		From(0).Size(10).   // take documents 0-9
		Pretty(true).       // pretty print request and response JSON
		Do(ctx)             // execute
	if err != nil {
		// Handle error
		panic(err)
	}
	fmt.Println(searchResult)
	//searchResult.Hits.Hits[0].Source
	return nil
}
